// 登录、注册
const express = require('express'); //引入express
const router = express.Router();
const qs = require('querystring');
const { User, userValidator } = require('../../models/users');
const { Role } = require('../../models/roles');
const { Menu } = require('../../models/menu');
const bcryptjs = require('bcryptjs');
var jwt = require('jsonwebtoken');
const auth = require('../../config.js/auth');
const validator = require('../../middleware/validate');
const equipmentInfo = require("../../tools/equipmentInfo"); // 获取设备信息
const axios = require('axios');
const { use } = require('passport');
// 测试接口
router.get('/test', async(req, res) => {
	// res.header("Access-Control-Allow-Origin", req.headers.origin);
	try {
    const response = await axios.get('https://apis.map.qq.com/ws/location/v1/ip?key=UO3BZ-IIVCD-EQJ4A-PPTHU-LBT6T-ADF5H');
    res.json(response.data);
  } catch (error) {
    res.status(500).send('Error fetching data');
  }
});

// 测试接口
router.post('/img', (req, res) => {
	console.log(req.body);
	res.header('Access-Control-Allow-Origin', req.headers.origin);
	res.json({ msg: 'login works' });
});
/**
 * @route GET api/equipment/info
 * @desc  获取电脑信息
 * @access 接口是公开的
 */
router.get("/equipment/info", async (ctx, res) => {
	console.log("33333333333");
	
	ctx.body = {
			status: 200,
			success: true,
			body: equipmentInfo,
	};
	res.json({ msg: equipmentInfo });
});

// 注册请求 post-需要安装模块 body-parser
router.post('/register', (req, res) => {
	console.log(req.params);
	User.findOne({ name: req.body.name }).then(user => {
		if (user) {
			return res.status(400).json({
				email: '用户被注册'
			});
		} else {
			const newUser = new User({
				name: req.body.name,
				password: req.body.password
			});
			// 密码加密
			bcryptjs.genSalt(10, function (err, salt) {
				bcryptjs.hash(newUser.password, salt, function (err, hash) {
					if (err) throw err;
					newUser.password = hash;
					newUser
						.save()
						.then(user => {
							res.json(user);
						})
						.catch(err => {
							console.log(err);
						});
				});
			});
		}
	});
});
// 登录接口-validator(userValidator),
router.post('/login', validator(userValidator), (req, res) => {
	try {
		User.findOne({ name: req.body.name })
			.then(async user => {
				if (!user) {
					return res.status('404').json({
						email: '用户不存在'
					});
				} else {
					// 通过用户角色查询菜单
					const menu = await Role.findById(user.role._id).populate('menu');
					bcryptjs.compare(req.body.password, user.password).then(isPwd => {
						if (isPwd) {
							let rule = {
								id: user.id,
								name: user.name,
								identity: user.identity
							};
							jwt.sign(rule, 'secret', { expiresIn: 7200 }, (err, token) => {
								if (err) throw err;
								user.role.menu = menu.menu;
								res.json({
									code: 200,
									success: true,
									data: {
										 user,token
									},
									token: 'Bearer ' + token
								});
							});
						} else {
							return res.status(400).json({
								password: '密码错误'
							});
						}
					});
				}
			});
	} catch (error) {
		console.log(error);
		next(error);
	}
});

// 获取菜单接口 getUserMenu
router.post('/getUserMenu/:id', async (req, res) => {
	// const user = await User.findById(req.params.id).populate('role');
	const menu = await Role.findById(req.params.id).populate('menu');
	res.status(200).json({
		code: 200,
		msg: '用户列表查询成功',
		data: menu.menu
	});
});

// 获取全部用户
router.get('/getUserList', auth, async (req, res, next) => {
	const { skip, limit, gender, deptId, createTime, name, _id } = req.query;
	try {
		const conditions = {};
		if (name) conditions.name = { $eq: name };
		if (_id) conditions._id = { $eq: _id };
		if (gender) conditions.gender = { $eq: gender };
		if (deptId) conditions.dept = { $eq: deptId };
		if (createTime)
			conditions.data = { $gte: createTime[0], $lte: createTime[1] };

		// 1.查询用户
		let total = await User.find(conditions);
		let userList = await User.find(conditions)
			.populate({ path: 'role', select: 'name' })
			.populate({ path: 'dept' })
			.skip((skip - 1) * limit)
			.limit(limit);

		if (!userList)
			return res.status(400).json({
				code: 400,
				msg: '用户列表不存在'
			});
		global.log.desc = "查询全部用户"
		console.log(global.log,"log");
		res.status(200).json({
			code: 200,
			msg: '用户列表查询成功',
			data: { userList, total: total.length }
		});
	} catch (err) {
		next(err);
	}
});
// 增加用户
router.post('/add', (req, res) => {
	// 1.查询数据库中是否有这个名字
	User.findOne({ name: req.body.name }).then(user => {
		if (user) {
			return res.status(400).json({
				email: '用户被注册'
			});
		} else {
			const newUser = new User({
				name: req.body.name,
				password: req.body.password,
				gender: req.body.gender,
				role: req.body.role,
				dept: req.body.dept
			});
			// 密码加密
			bcryptjs.genSalt(10, function (err, salt) {
				bcryptjs.hash(newUser.password, salt, function (err, hash) {
					if (err) throw err;
					newUser.password = hash;
					newUser
						.save()
						.then(user => {
							res.json({
								code: 200,
								msg: '新增用户成功',
								data: user
							});
						})
						.catch(err => {
							console.log(err);
						});
				});
			});
		}
	});
});
// 删除用户
router.post('/delete/:id', (req, res) => {
	User.findByIdAndDelete({ _id: req.params.id })
		.then(profile => {
			console.log(profile);
			res.json({
				data: profile,
				msg: '删除成功'
			});
		})
		.catch(err => {
			res.json({
				data: err,
				msg: '删除失败'
			});
		});
});
// 更新用户资料
router.post('/updateUser/:id', async (req, res) => {
	let _id = req.params.id;
	let body = req.body;
	console.log('body,_id', body, _id);

	// 1.查询用户并修改
	const data = await User.findByIdAndUpdate(_id, body);
	console.log('data', data);
	// 2.更新失败
	if (!data)
		res.status(400).json({
			code: 400,
			msg: '更新用户失败'
		});
	// 3.更新成功
	res.status(200).json({
		code: 200,
		msg: '更新成功',
		data: { body }
	});
}),
	// 数据接口
	router.get('/current', auth, async (req, res) => {
		try {
			res.status(200).json(req.user);
		} catch (error) {
			res.status(400).json(error);
		}
	});

module.exports = router;
